package org.halk.controller;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class PdfExportController {

    @Autowired
    private TemplateEngine templateEngine;

    @GetMapping("/export-pdf2")
    public void exportPdf2(HttpServletResponse response) throws Exception {

        String siteName = "北京师范大学";
        String projectId = "HOR";
        String projectName = "横断";
        String createDateStr = "2024-01-01 09:09";

        //封面数据
        Map<String, String> headMap = new HashMap<>();
        headMap.put("siteName", siteName);
        headMap.put("projectName", projectName + "正式采集数据质量分析报告");
        headMap.put("createDateStr", "该份报告的统计时间截止到 " + createDateStr);


        Map<String, Object> objMap = new HashMap<>();
        objMap.put("head", headMap);
        objMap.put("baseUri", getBaseUri());
//        objMap.put("items", items);

        String pdfPath = "E:/1.pdf";
//        Context context = new Context();
//        objMap.forEach(context::setVariable);

//        context.setVariable("baseUri", getBaseUri());
//        context.setVariable("siteName", siteName);
//
////        context.setVariable("siteName", templateEntity.getSiteName());
////        context.setVariable("subjectName", templateEntity.getSubjectName());
////        context.setVariable("subjectId", templateEntity.getSubjectId());
////        context.setVariable("time", templateEntity.getTime());
//        String htmlStr = templateEngine.process("report", context);
//        HtmlToPdfUtils.convertStringToPdf(htmlStr, pdfPath);

        convertToPdf(objMap);
    }


    public String getBaseUri() {
        try {
            Resource resource = new ClassPathResource("file/templates/");
            return resource.getURL().toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }


    private void convertToPdf(Map<String, Object> objMap) throws IOException {
        // 创建Thymeleaf上下文
        Context context = new Context();
        objMap.forEach(context::setVariable);

        // 渲染模板为HTML
        String html = templateEngine.process("report", context);

        // 创建PDF
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html);
        renderer.layout();


        // 将List集合写入文件
        FileOutputStream fos = new FileOutputStream("report.pdf");
        baos.writeTo(fos);
        fos.flush();
        fos.close();
    }


    @GetMapping("/export-pdf")
    public void exportPdf(HttpServletResponse response) throws Exception {
        // 准备数据
        List<Item> items = new ArrayList<>();
        items.add(new Item(1, "Item 1", 100));
        items.add(new Item(2, "Item 2", 200));

        Map<String, Object> objMap = new HashMap<>();
        objMap.put("head", "this is pdf 的头部");
        objMap.put("items", items);
        objMap.put("baseUri", getBaseUri());

        String siteName = "北京师范大学";
        String projectId = "HOR";
        String projectName = "横断";
        String createDateStr = "2024-01-01 09:09";

        //封面数据
        Map<String, String> headMap = new HashMap<>();
        headMap.put("siteName", siteName);
        headMap.put("projectName", projectName + "正式采集数据质量分析报告");
        headMap.put("createDateStr", "该份报告的统计时间截止到 " + createDateStr);

        objMap.put("head", headMap);

        convertToPdf(response, "report", objMap);
    }

    private void convertToPdf(HttpServletResponse response, String htmlPath, Map<String, Object> objMap) throws IOException, DocumentException {
        // 创建Thymeleaf上下文
        Context context = new Context();
        objMap.forEach(context::setVariable);

        // 渲染模板为HTML
        String html = templateEngine.process(htmlPath, context);

        // 创建PDF
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(html);

        // 在生成 PDF 之前，设置支持中文的字体
//        renderer.getFontResolver().addFont("file/templates/ttf/simhei.ttf", true);
//        renderer.getFontResolver().addFont("E:/simhei.ttf", true);
        renderer.getFontResolver().addFont("E:/楷体_GB2312.ttf", "UTF-8", BaseFont.NOT_EMBEDDED);

        renderer.layout();
        renderer.createPDF(baos);

        // 设置响应头
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=export.pdf");

        // 输出PDF到响应流
        OutputStream os = response.getOutputStream();
        baos.writeTo(os);
        os.flush();
        os.close();
    }

    // 示例数据类
    public static class Item {
        private int id;
        private String name;
        private int value;

        public Item(int id, String name, int value) {
            this.id = id;
            this.name = name;
            this.value = value;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public int getValue() {
            return value;
        }
    }
}
   